//
//  CountViewController.m
//  Article
//
//  Created by LONG on 16/4/21.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "CountViewController.h"
#import "MyTools.h"
#import "CountTableViewCell.h"
#import "AFNetworking.h"
#import "UIView+Toast.h"
#import "SDWebImageManager.h"
#import "MJRefresh.h"
#import "EditViewController.h"
#import "MaterialViewController.h"
#import "UITabBar+NumberOfTabbar.h"

#import <AVFoundation/AVFoundation.h>
#import "QRCodeController.h"
#import "AppDelegate.h"

@interface CountViewController ()<UITableViewDelegate,UITableViewDataSource>{
    //    UIButton *_topbtn1;
    //    UIButton *_topbtn2;
    //    UIButton *_topbtn3;
    //    UIButton *_topbtn4;
    
    UITableView *_mytab;
    NSString *_typeStr;
    NSMutableArray *_dataArray;
    NSMutableDictionary *_countDic;
    __block int page;
    AppDelegate *del;
}

@end

@implementation CountViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    _typeStr = @"spread";
    _dataArray = [NSMutableArray array];
    
    del = (AppDelegate *)[UIApplication sharedApplication].delegate;

    self.view.backgroundColor = UIColorFromRGB(0xefeff1);
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont fontWithName:@"Heiti SC" size:18],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    //二维码
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"Unknown-1"] style:UIBarButtonItemStylePlain target:self action:@selector(intoQRCodeVC)];
    [self.navigationItem.rightBarButtonItem setTintColor:UIColorFromRGB(0xffffff)];
    //nav底部线消失
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    
    [self.navigationController.navigationBar setBarTintColor:UIColorFromRGB(MYColor)];
    
    //侧滑返回
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate =(id)self;
    
    //直接进入的推送
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushSomething) name:@"icon" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushSomething) name:@"backicon" object:nil];
    
    [self viewCreate];
    
    [self loadThisPageData];
    
}

-(void)pushSomething{
    [self.tabBarController.tabBar showBadgeOnItemIndex:3];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:@"YES" forKey:@"isMessage"];
    [user synchronize];
}
//-(void)pushAnything:(NSNotification *)notification{
////    NSLog(@"+++===%@",[notification.userInfo objectForKey:@"where"]);
//    [self.tabBarController.tabBar hideBadgeOnItemIndex:3];
//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    [user setObject:@"NO" forKey:@"isMessage"];
//    [user synchronize];
//        
////        MaterialViewController *mater = [[MaterialViewController alloc]init];
////        [self.navigationController pushViewController:mater animated:YES];
//    
//   
//    
//    
//    
//   
//}

//下拉刷新
-(void)downMJ{
    page = 1;
    [self loadThisPageData];
    
    [_mytab.header endRefreshing];
}
//上拉加载
- (void)loadMoreData{
    page++;
    [self loadThisPageData];
    [_mytab.footer endRefreshing];
    
}


-(void)viewCreate{
    
    
    NSArray *arr = [NSArray arrayWithObjects:@"推广文章",@"素材点击",@"素材曝光",@"更新时间", nil];
    
    UIView *heardview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 35)];
    heardview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:heardview];
    
    UIView *lineview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 0.6)];
    lineview.backgroundColor = UIColorFromRGB(0xf2f2f2);
    [heardview addSubview:lineview];
    
    for (int i = 0; i < arr.count; i++) {
        UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(10 + (WIDTH - 20) / 4 * i, 1, (WIDTH - 20) / 4, 34)];
        btn.backgroundColor = [UIColor whiteColor];
        btn.tag = 101 + i;
        btn.titleLabel.font = [UIFont fontWithName:@"Heiti SC" size:14];
        [btn setTitle:[arr objectAtIndex:i] forState:UIControlStateNormal];
        if (i == 0) {
            [btn setTitleColor:UIColorFromRGB(MYColor) forState:UIControlStateNormal];
        }else{
            [btn setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
            //[btn setTitleColor:UIColorFromRGB(MYColor) forState:UIControlStateSelected];
        }
        
        [btn addTarget:self action:@selector(btnclick:) forControlEvents:UIControlEventTouchUpInside];
        [heardview addSubview:btn];
        
    }
    UIView *lineview1 = [[UIView alloc]initWithFrame:CGRectMake(0, 34, WIDTH, 0.6)];
    lineview1.backgroundColor = UIColorFromRGB(0xf2f2f2);
    [heardview addSubview:lineview1];
    
    _mytab = [[UITableView alloc]initWithFrame:CGRectMake(0, 35, WIDTH, HEIGHT - 140)];
    _mytab.backgroundColor = [UIColor whiteColor];
    _mytab.showsVerticalScrollIndicator = NO;
    _mytab.separatorStyle = UITableViewCellSeparatorStyleNone;
    _mytab.dataSource = self;
    _mytab.delegate = self;
    _mytab.rowHeight = 60;
    [self.view addSubview:_mytab];
    [_mytab addGifHeaderWithRefreshingTarget:self refreshingAction:@selector(downMJ)];
    
}



#pragma mark tabview代理

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_dataArray.count <= 0) {
        return 0;
    }
    return _dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell";
    CountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[CountTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    [cell.titleimage sd_setImageWithURL:_dataArray[indexPath.row][@"writing_img"] placeholderImage:[UIImage imageNamed:@"moren"]];
    cell.looklab.text = _dataArray[indexPath.row][@"xposed"];
    cell.clicklab.text = _dataArray[indexPath.row][@"view"];
    cell.timelab.text = _dataArray[indexPath.row][@"update_time"];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    EditViewController *editVC = [[EditViewController alloc]init];
    editVC.writing_img = _dataArray[indexPath.row][@"writing_img"];
    editVC.writing_title = _dataArray[indexPath.row][@"writing_title"];
    editVC.id = _dataArray[indexPath.row][@"writing_id"];
    
    [self.navigationController pushViewController:editVC animated:YES];
}

#pragma mark btn
-(void)btnclick:(UIButton *)btn{
    UIButton *topbtn1 = (id)[self.view viewWithTag:101];
    UIButton *topbtn2 = (id)[self.view viewWithTag:102];
    UIButton *topbtn3 = (id)[self.view viewWithTag:103];
    UIButton *topbtn4 = (id)[self.view viewWithTag:104];
    
    [topbtn1 setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    [topbtn2 setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    [topbtn3 setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    [topbtn4 setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    
    //    [topbtn1 setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateSelected];
    //    [topbtn2 setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateSelected];
    //    [topbtn3 setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateSelected];
    //    [topbtn4 setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateSelected];
    
    
    //btn.selected = !btn.selected;
    
    NSLog(@"%ld",(long)btn.tag);
    if (btn.tag == 101) {
        [btn setTitleColor:UIColorFromRGB(MYColor) forState:UIControlStateNormal];
        topbtn1.userInteractionEnabled = NO;
        topbtn2.userInteractionEnabled = YES;
        topbtn3.userInteractionEnabled = YES;
        topbtn4.userInteractionEnabled = YES;
        
        _typeStr = @"spread";
        
        [self loadThisPageData];
        
    }else if (btn.tag == 102){
        [btn setTitleColor:UIColorFromRGB(MYColor) forState:UIControlStateNormal];
        topbtn1.userInteractionEnabled = YES;
        topbtn2.userInteractionEnabled = NO;
        topbtn3.userInteractionEnabled = YES;
        topbtn4.userInteractionEnabled = YES;
        
        _typeStr = @"xposed";
        
        [self loadThisPageData];
        
    }else if (btn.tag == 103){
        [btn setTitleColor:UIColorFromRGB(MYColor) forState:UIControlStateNormal];
        topbtn1.userInteractionEnabled = YES;
        topbtn2.userInteractionEnabled = YES;
        topbtn3.userInteractionEnabled = NO;
        topbtn4.userInteractionEnabled = YES;
        
        _typeStr = @"view";
        
        [self loadThisPageData];
        
    }else if (btn.tag == 104){
        [btn setTitleColor:UIColorFromRGB(MYColor) forState:UIControlStateNormal];
        topbtn1.userInteractionEnabled = YES;
        topbtn2.userInteractionEnabled = YES;
        topbtn3.userInteractionEnabled = YES;
        topbtn4.userInteractionEnabled = NO;
        
        _typeStr = @"time";
        
        [self loadThisPageData];
    }
}

-(void)loadThisPageData{
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    NSUserDefaults *user = [[NSUserDefaults alloc]init];
    
    
    NSDictionary *dic =@{@"user_token":[user objectForKey:@"token"],
                         @"type":[NSString stringWithFormat:@"%@",_typeStr]};
    
    [manager POST:STATISTICS_URL parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject){
        _countDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        [_dataArray removeAllObjects];
        for (NSDictionary *dataDic in _countDic[@"data"]) {
            
            [_dataArray addObject:dataDic];
            
        }
        if (_dataArray.count > 7) {
            [_mytab addGifFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        }
        [_mytab reloadData];
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
    }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
              [self.view makeToast:@"暂无数据！" duration:0.5 position:CSToastPositionCenter];
              NSLog(@"网络连接失败");
          }];
    
}

#pragma mark 侧滑删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        NSUserDefaults *user = [[NSUserDefaults alloc]init];
        
        
        NSDictionary *dic =@{@"user_token":[user objectForKey:@"token"],
                             @"id":_dataArray[indexPath.row][@"id"]};
        
        [manager POST:DELSPREAD_URL parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject){
            _countDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            
            [_mytab reloadData];
        }
              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  NSLog(@"网络连接失败");
              }];
        
        [_dataArray removeObjectAtIndex:indexPath.row];
        // Delete the row from the data source.
        [_mytab deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

-(void)viewWillAppear:(BOOL)animated{
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.navigationController.navigationBar.translucent = NO;//透明

    self.tabBarController.tabBar.hidden = NO;
    self.tabBarController.tabBar.translucent = NO;
}


/**
 *  是否可以打开设置页面
 *
 *  @return
 */
- (BOOL)canOpenSystemSettingView {
    if (IS_VAILABLE_IOS8) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            return YES;
        } else {
            return NO;
        }
    } else {
        return NO;
    }
}

/**
 *  跳到系统设置页面
 */
- (void)systemSettingView {
    if (IS_VAILABLE_IOS8) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

/*!
 *  扫一扫
 */
- (void)intoQRCodeVC {
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(authStatus == AVAuthorizationStatusDenied){
        if (IS_VAILABLE_IOS8) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"相机权限受限" message:@"请在iPhone的\"设置->隐私->相机\"选项中,允许\"拇指营销\"访问您的相机." preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            }]];
            [alert addAction:[UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                if ([self canOpenSystemSettingView]) {
                    [self systemSettingView];
                }
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"相机权限受限" message:@"请在iPhone的\"设置->隐私->相机\"选项中,允许\"拇指营销\"访问您的相机." delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
            [alert show];
        }
        
        return;
    }
   
    QRCodeController *qrcodeVC = [[QRCodeController alloc] init];
    qrcodeVC.view.alpha = 0;
    [qrcodeVC setDidReceiveBlock:^(NSString *result) {
        NSLog(@">>>>>%@", result);
        if (result.length > 4) {
            NSString * string = [result substringToIndex:4];//截取下标4之前的字符串
            
            NSString *str = [result substringFromIndex:4];//截取下标4之后的字符串
            
            if ([string isEqualToString:@"拇指营销"]) {
                [self qrcodeVCNSStr:str];
            }else{
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请扫描分享二维码" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
            }
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请扫描分享二维码" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
        
    }];
    [del.window.rootViewController addChildViewController:qrcodeVC];
    [del.window.rootViewController.view addSubview:qrcodeVC.view];
    [UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        qrcodeVC.view.alpha = 1;
    } completion:^(BOOL finished) {
    }];
}
- (void)qrcodeVCNSStr:(NSString *)str{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *urlstr = SHARE_SCAN_URL;
    NSDictionary *dic = @{@"user_token":[user objectForKey:@"token"],
                          @"link":str};
    
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    
    [manager POST:urlstr parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"///%@",dic1);
        
        [self.view makeToast:[dic1 objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        //NSLog(@"=====>%@",error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        if ([MyTools connectedToNetwork] == 0) {
            [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
        }else{
            [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
        }
        
    }];

}
-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"icon" object:nil];
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"backicon" object:nil];
}
@end
